﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 初始化创建的时候 有问题， 有个player会移动一段时间
// server的消息处理能力需要优化 interval为9就只能支持3个客户端
// keep alive

public class ShadowInfo
{
    public Vector3 m_Pos; 
}

public class Player : MonoBehaviour
{
    [SerializeField] float m_MoveSpeed = 5f;
    Transform m_Trans;
    public ulong UserID { private set; get; }
    readonly uint m_TickInterval = 3;
    uint m_LastPosSyncTickCount;
    ShadowInfo m_Shadow = new ShadowInfo(); 

    public Transform CacheTrans
    {
        get
        {
            if (m_Trans == null)
            {
                m_Trans = this.transform;
            }
            return m_Trans;
        }
    }

    public bool IsLocalPlayer()
    {
        return Facade.LocalUserID == UserID;
    }

    public void Init(ulong userId, Vector3 pos)
    {
        CacheTrans.position = pos;
        UserID = userId;
    }

    public void UpdatePos(uint tickCount, Vector3 pos)
    {
        if (tickCount <= m_LastPosSyncTickCount)
        {
            return;
        }
        m_LastPosSyncTickCount = tickCount; 
        m_Shadow.m_Pos = pos;
    }

    void Update()
    {
        if (!IsLocalPlayer())
        {
            if (Vector3.Distance(m_Shadow.m_Pos, CacheTrans.position) < 0.1f)
            {
                return;
            }

            // teleport
            if (Vector3.Distance(m_Shadow.m_Pos, CacheTrans.position) > 10f)
            {
                CacheTrans.position = m_Shadow.m_Pos; 
                return;
            }

            var dir = m_Shadow.m_Pos - CacheTrans.position;
            CacheTrans.position += dir.normalized * m_MoveSpeed * Time.deltaTime; 
            // do not predict?
            return;
        }

        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        if (h != 0 || v != 0)
        {
            CacheTrans.position += new Vector3(h, 0, v).normalized * m_MoveSpeed * Time.deltaTime;
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            //m_NeedSend = !m_NeedSend;
            //MessageManager.Instance.Send(new C2S_PlayerSync { PosX = CacheTrans.position.x, PosY = CacheTrans.position.y, PosZ = CacheTrans.position.z });
        }
    }

    private void FixedUpdate()
    {
        FixedTick();
    }

    //bool m_NeedSend = true;
    public void FixedTick()
    {
        if (IsLocalPlayer())
        {
            if (Facade.TickCount % m_TickInterval == 0)
            {
                MessageManager.Instance.Send(new C2S_PlayerSync { TickCount = Facade.TickCount, PosX = CacheTrans.position.x, PosY = CacheTrans.position.y, PosZ = CacheTrans.position.z });
            }
        }
    }
}
